package cn.javabb.admin.controller.sys;

import cn.javabb.common.exception.ParameterException;
import cn.javabb.common.model.ResponseModel;
import cn.javabb.common.utils.BUtil;
import cn.javabb.core.base.BaseController;
import cn.javabb.core.entity.sys.RoleDO;
import cn.javabb.core.entity.sys.UserDO;
import cn.javabb.core.service.sys.RoleService;
import cn.javabb.core.service.sys.UserAuthService;
import cn.javabb.core.service.sys.UserService;
import cn.javabb.core.service.sys.UsersRolesService;
import cn.javabb.log.action.DeleteAction;
import cn.javabb.log.action.StateAction;
import cn.javabb.log.action.UserAction;
import cn.javabb.log.annotation.EntityParam;
import cn.javabb.log.annotation.Log;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/user")
public class UserAdminController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UsersRolesService usersRolesService;
    @Autowired
    private UserAuthService userAuthService;
    /**
     * 用户列表页面
     * @author QINB
     * @param model
     * @return
     */
    @RequiresPermissions("user:view")
    @GetMapping("/list")
    public String toListPage(Model model) {
        List<RoleDO> roles = roleService.queryAll();
        model.addAttribute("roles", roles);
        return "admin/system/user";
    }
    /**
     * 用户保存页面
     * @author QINB
     * @param model
     * @return
     */
    @GetMapping("/save")
    public String toSavePage(Model model) {
        List<RoleDO> roles = roleService.queryAll();
        model.addAttribute("roles", roles);
        return "admin/system/userSave";
    }

    /**
     * 查询用户列表
     */
    @RequiresPermissions("user:view")
    @ResponseBody
    @GetMapping("/")
    public Object list(String searchKey,String searchValue) {
        String page = getPage();
        String size = getSize();
        if (StringUtils.isBlank(searchValue)) {
            searchKey = null;
        }
        JSONObject param = new JSONObject();
        param.put("page", page);
        param.put("size", size);
        if("userName".equals(searchKey)){
            param.put("userName", searchValue);
        }
        if("phone".equals(searchKey)){
            param.put("phone", searchValue);
        }
        if("eamil".equals(searchKey)){
            param.put("eamil", searchValue);
        }
        Page userPage = userService.listUserPage(param);
        return ResponseModel.table(userPage);
    }
    /**
     * 添加或更新用户
     **/
    @RequiresPermissions("user:edit")
    @ResponseBody
    @PostMapping("/")
    @Log(key= UserAction.USER_SAVE,action = UserAction.class)
    public Object save(@EntityParam UserDO user,String userPwd){
        if(BUtil.isNull(user)){
            return ResponseModel.Failure("参数错误,保存失败");
        }
        int num = 0;
        String roleIds = getParamValue("roleId");
        if(BUtil.isNull(user.getId())){
            //insert
            if(userService.queryUsernameRepeat(user.getUserName())){
                return ResponseModel.Failure("用户名不能重复，请重新输入");
            }
            UserDO u = userService.addUser(user, userPwd);
            if (null != null) {
                //保存用户角色
                roleService.saveUsersRoles(user.getId(), roleIds);
                num = 1;
            }
        }else{
            //update 
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("userName", user.getUserName());
            if(userService.queryRepeat(UserDO.class, "id",user.getId(),map)){
                return ResponseModel.Failure("用户名已经存在，请重新输入");
            }
            //update
            num = userService.updateSelective(user);
            if(num>0 && StringUtils.isNotBlank(roleIds)){
                roleService.updateUsersRoles(user.getId(), roleIds);
            }
        }
        if(num>0){
            return ResponseModel.Success("保存成功");
        }
        return ResponseModel.Failure("保存失败");
    }
    

    private List<RoleDO> getRoles(String roleStr) {
        List<RoleDO> roles = new ArrayList<>();
        String[] split = roleStr.split(",");
        for (String t : split) {
            if (t.equals("1")) {
                throw new ParameterException("不能添加超级管理员");
            }
           RoleDO role = new RoleDO();
           role.setId(Integer.parseInt(t));
           roles.add(role);
        }
        return roles;
    }

    /**
     * 修改用户状态
     **/
    @RequiresPermissions("user:del")
    @ResponseBody
    @PostMapping("/updateState")
    @Log(name="用户状态",action = StateAction.class)
    public Object updateState(@RequestParam String ids, Integer state) {
        if (userService.updateState(ids, state)) {
            return ResponseModel.Success("更新成功");
        } else {
            return ResponseModel.Failure("更新失败");
        }
    }
    @RequiresPermissions("user:del")
    @ResponseBody
    @DeleteMapping("/{ids}")
    @Log(name = "用户删除",action = DeleteAction.class)
    public Object delete(@PathVariable String ids){
        if(StringUtils.isBlank(ids)){
            return ResponseModel.Failure("参数错误");
        }
        if (userService.delete(ids)) {
            return ResponseModel.Success("删除成功");
        }
        return ResponseModel.Failure("删除失败");
    }


}
